package com.yf.ability.login.wechat.utils;

import com.alibaba.fastjson.JSON;
import com.yf.ability.login.wechat.dto.response.WxInfoRespDTO;
import com.yf.ability.login.wechat.dto.response.WxLoginRespDTO;
import com.yf.ability.login.wechat.dto.response.WxTokenRespDTO;
import com.yf.base.utils.http.HttpClientUtil;
import lombok.extern.log4j.Log4j2;

/**
 * 用户登录工具类
 * @author bool
 * @date 2021/8/3 14:53
 */
@Log4j2
public class LoginUtils {

    /**
     * 登录请求地址
     */
    private static final String TOKEN_URL = "https://api.weixin.qq.com/sns/jscode2session?appid={appId}&secret={appSecret}&js_code={code}&grant_type=authorization_code";

    /**
     * 获取AccessToken
     */
    private static final String ACCESS_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={appId}&secret={appSecret}&code={code}&grant_type=authorization_code";

    /**
     * 获取用户信息接口
     */
    private static final String INFO_URL = "https://api.weixin.qq.com/sns/userinfo?access_token={token}&openid={openid}";


    /**
     * 通过微信code获得用户信息
     * @param appId
     * @param appSecret
     * @param code
     * @return
     */
    public static WxLoginRespDTO requestLogin(String appId, String appSecret, String code){

        // 构建完整请求URL
        String url = TOKEN_URL.replace("{appId}", appId)
                .replace("{appSecret}", appSecret)
                .replace("{code}", code);

        // 获得返回JSON
        String json = HttpClientUtil.getJson(url, null, null);
        // 转换为登录结果
        WxLoginRespDTO rest = JSON.parseObject(json, WxLoginRespDTO.class);
        return rest;
    }



    /**
     * 获取用户头像昵称等内容
     * @param appId
     * @param appSecret
     * @return
     */
    public static WxInfoRespDTO requestInfo(String appId, String appSecret, String code){

        // 获取accessToken
        WxTokenRespDTO token = requestAccess(appId, appSecret, code);

        // 获取用户信息
        String url = INFO_URL
                .replace("{token}", token.getAccessToken())
                .replace("{openid}", token.getOpenid());

        String json = HttpClientUtil.getJson(url, null, null);
        WxInfoRespDTO rest = JSON.parseObject(json, WxInfoRespDTO.class);

        return rest;
    }


    /**
     * 获取accessToken
     * @param appId
     * @param appSecret
     * @param code
     * @return
     */
    public static WxTokenRespDTO requestAccess(String appId, String appSecret, String code){

        // 构建完整请求URL
        String url = ACCESS_URL.replace("{appId}", appId)
                .replace("{appSecret}", appSecret)
                .replace("{code}", code);

        // 获得返回JSON
        String json = HttpClientUtil.getJson(url, null, null);

        log.info(json);

        // 转换为登录结果
        WxTokenRespDTO rest = JSON.parseObject(json, WxTokenRespDTO.class);

        return rest;
    }
}
